package cn.redragon.soa.common.amqp;

import com.rabbitmq.client.Channel;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.api.RabbitListenerErrorHandler;
import org.springframework.amqp.rabbit.support.ListenerExecutionFailedException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

@Slf4j
@Component("listenerErrorHandler")
@ConditionalOnClass({RabbitTemplate.class, Channel.class})
public class ListenerErrorHandler implements RabbitListenerErrorHandler {

    @Override
    public Object handleError(Message amqpMessage, org.springframework.messaging.Message<?> message, ListenerExecutionFailedException exception) {
        String consumerQueue = exception.getFailedMessage().getMessageProperties().getConsumerQueue();
        log.error("Failed to process message from queue {}; failed message: {}; exception detail: {}", consumerQueue, new String(amqpMessage.getBody(), StandardCharsets.UTF_8), exception);
        throw new AmqpRejectAndDontRequeueException(exception);
    }
}